package mobi.bantu.web;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import mobi.bantu.bean.BaseController;
import mobi.bantu.bean.Cons;
import mobi.bantu.bean.Result;
import mobi.bantu.bean.User;
import mobi.bantu.config.SysConf;
import mobi.bantu.service.UserService;
import mobi.bantu.utils.CodeUtils;
import mobi.bantu.utils.DateUtils;
import mobi.bantu.utils.WeixinTools;
import sun.misc.BASE64Decoder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * Created by qiao on 2017/9/9.
 */
@Controller
public class HomeController extends BaseController {
    static final String DEFAULT_PAGE = "index";
    static BASE64Decoder decoder = new sun.misc.BASE64Decoder();
    private static Logger log = LoggerFactory.getLogger(HomeController.class);

    @Resource
    private UserService userService;
    private final ResourceLoader resourceLoader;

    @Autowired
    public HomeController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @RequestMapping("/")
    public String index(){
       return  "index";
    }

    @RequestMapping("base")
    public String base(HttpServletRequest request) {
        return paymentCallback(request);
    }

    @RequestMapping("home")
    public String home(HttpServletRequest request, Model model) {
        User user = getSessionUser(request);
        if (user == null) return Cons.ERROR_PAGE;
        model.addAttribute("user", user);
        model.addAttribute("view", userService.view(user));
        return DEFAULT_PAGE;
    }

    @RequestMapping("tologin")
    public String toLogin() {
        return "login";
    }

    private String paymentCallback(HttpServletRequest request) {
        String code = request.getParameter("code");
        String openId = request.getParameter("openid");
        System.out.println("==================================code:" + code);
        User user = null;
        if (StringUtils.isNotBlank(openId) &&
                StringUtils.equals(SysConf.get("spring.profiles.active"), "develop")) {
            user = userService.getByOpenId(openId);
            if (user == null) {
                user = userService.createNewUser(openId);
            }
            setSessionUser(request, user);
            return "forward:/home.do";
        }
        if (code != null) {
            String wechatNo = null;
            String result_str = WeixinTools.getAuthToken(code);
            if (result_str != null && result_str.contains("access_token")) {
                JSONObject obj = JSON.parseObject(result_str);
                log.info("openid ===" + obj.toJSONString());
                if (!obj.containsKey("openid")) return "error";
                wechatNo = obj.getString("openid");
                user = userService.getByOpenId(wechatNo);
                if (user == null) {
                    user = userService.createNewUser(wechatNo);
                    System.out.println("============ wechatNo:" + wechatNo);
                }
                setSessionUser(request, user);
            }
        }
        return "forward:/home.do";
    }

    @RequestMapping("redirect")
    public String redirect(String to) {
        return to;
    }

    @RequestMapping(value = "/upload/{filename:.+}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<?> getFile(@PathVariable String filename) {
        try {
            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(Cons.FILE_ROOT, filename).toString()));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.notFound().build();
        }
    }

    @RequestMapping(value = "imgUpload", method = RequestMethod.POST)
    @ResponseBody
    public Result imgUpload(HttpServletRequest request) {
        try {
            String base64Str = request.getParameter("formFile");
            if (StringUtils.isBlank(base64Str)) return Result.byMsg("参数为空");
            log.info("imgBase64{}", StringUtils.substringBefore(base64Str, ";"));
            byte[] imgBytes = decoder.decodeBuffer(StringUtils.substringAfter(base64Str, ";base64,"));
            for (int i = 0; i < imgBytes.length; ++i) {
                if (imgBytes[i] < 0) {//调整异常数据
                    imgBytes[i] += 256;
                }
            }
            InputStream inputStream = new ByteArrayInputStream(imgBytes);
            String fileName = DateUtils.formatTime(new Date()) + "." + CodeUtils.getImgSuffix(base64Str);
            log.info("图片上传fileName: " + fileName);
            try {
                Files.copy(inputStream, Paths.get(Cons.FILE_ROOT, fileName));
            } catch (Exception e) {
                e.printStackTrace();
                return Result.byMsg(e.getMessage());
            }
            return Result.success(fileName);
        } catch (Exception e) {
            return Result.byMsg("上传失败" + e.getMessage());
        }
    }
}
